﻿using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.WowAddonStudio.Services;

namespace Microsoft.WowAddonStudio.Lua.LanguageService.Support
{
    /// <summary>
    /// Library manager used to track the currently loaded addon project hierarchies.
    /// </summary>
    [Guid(GuidStrings.LibraryManager)]
    public class LibraryManager : ILibraryManager
    {
        private readonly Dictionary<IVsHierarchy, HierarchyManager> hierarchies = new Dictionary<IVsHierarchy, HierarchyManager>();

        private readonly IServiceProvider serviceProvider;

        public LibraryManager(IServiceProvider serviceProvider)
        {
            if (serviceProvider == null) 
                throw new ArgumentNullException("serviceProvider");

            this.serviceProvider = serviceProvider;
        }

        /// <summary>
        /// Registers a hierarchy in the library.
        /// </summary>
        /// <param name="hierarchy">The hierarchy to register.</param>
        public void RegisterHierarchy(IVsHierarchy hierarchy)
        {
            if (hierarchy == null || hierarchies.ContainsKey(hierarchy))
                return;

            // Create hierarchy manager for hierarchy
            var hierarchyManager = new HierarchyManager(serviceProvider, hierarchy);

            hierarchies.Add(hierarchy, hierarchyManager);
        }

        /// <summary>
        /// Unregisters a hierarchy in the library.
        /// </summary>
        /// <param name="hierarchy">The hierarchy to unregister.</param>
        public void UnregisterHierarchy(IVsHierarchy hierarchy)
        {
            if (hierarchy == null || !hierarchies.ContainsKey(hierarchy))
                return;

            hierarchies.Remove(hierarchy);
        }

        /// <summary>
        /// Gets the hierarchy managers currently registered in the library.
        /// </summary>
        public IEnumerable<HierarchyManager> HierarchyManagers
        {
            get { return hierarchies.Values; }
        }
    }
}